package io.valuesfeng.picker;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.valuesfeng.picker.adapter.PreviewImagePaperAdapter;
import io.valuesfeng.picker.widget.HackyViewPager;

public class PreviewImageActivity extends AppCompatActivity
        implements PreviewImagePaperAdapter.OnItemPhotoTapListener, ViewPager.OnPageChangeListener {


    public static final String EXTRA_IMAGES = "image_items";
    public static final String EXTRA_HAS_SAVE = "has_save";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    ProgressBar processBar;
    HackyViewPager hvpImage;
    ImageView titleImgvLeftIcon;
    TextView toolbarTitle;
    ImageButton btnSaveImg;
    RelativeLayout rlActionBar;
    private int imageIndex;
    private ArrayList<String> images;
    private boolean actionIsShow = true;
    private boolean hasSave = false;

    public static void startActivity(Activity activity, List<String> images, int imageIndex, Boolean hasSave) {

        Intent intent = new Intent(activity, PreviewImageActivity.class);
        intent.putExtra(EXTRA_IMAGE_INDEX, imageIndex);
        intent.putStringArrayListExtra(EXTRA_IMAGES, (ArrayList<String>) images);
        intent.putExtra(EXTRA_HAS_SAVE, hasSave);

        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_image);

        if (savedInstanceState == null) {
            onInitInstanceStateFromIntent();
        } else {
            onRestoreInstanceStateFromBundle(savedInstanceState);
        }
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {

        processBar = (ProgressBar) findViewById(R.id.process_bar);
        hvpImage = (HackyViewPager) findViewById(R.id.hvp_image);
        titleImgvLeftIcon = (ImageView) findViewById(R.id.title_imgv_left_icon);
        toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
        btnSaveImg = (ImageButton) findViewById(R.id.btn_save_img);
        rlActionBar = (RelativeLayout) findViewById(R.id.rl_action_bar);
        if (images != null && images.size() > 1) {

            toolbarTitle.setText(getString(R.string.image_index_count_format, imageIndex + 1, images.size()));
        }

        PreviewImagePaperAdapter previewImagePaperAdapter = new PreviewImagePaperAdapter(images, this);
        hvpImage.setAdapter(previewImagePaperAdapter);
        previewImagePaperAdapter.setOnItemPhotoTapListener(this);
        hvpImage.setCurrentItem(imageIndex);
        if (hasSave) {
            btnSaveImg.setVisibility(View.VISIBLE);
        }
        titleImgvLeftIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

        hvpImage.addOnPageChangeListener(this);
        btnSaveImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                saveImage();
            }
        });
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        imageIndex = position;
        toolbarTitle.setText(getString(R.string.image_index_count_format, imageIndex + 1, images.size()));
        setProcessShow(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPhotoTap(View view, float x, float y) {

        if (actionIsShow) {
            rlActionBar.animate().translationY(-rlActionBar.getHeight()).setInterpolator(new AccelerateInterpolator(2)).start();
            actionIsShow = false;

        } else {

            rlActionBar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
            actionIsShow = true;
        }
    }

    public void saveImage() {

        Glide.with(this).load(images.get(imageIndex)).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                saveBitmapToSdCard(PreviewImageActivity.this, resource, getExternalCacheDir());
            }
        });
    }

    public boolean saveBitmapToSdCard(Context context, Bitmap bitmap, File parent) {
        boolean save = false;
        if (bitmap == null) {
            return save;
        }
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return save;
        }


        FileOutputStream out = null;
        File f = null;
        try {


            long millis = Calendar.getInstance().getTimeInMillis();
            f = new File(parent, millis + ".jpg");


            if (!parent.exists()) {
                parent.mkdirs();
            }
            boolean createNewFile = f.createNewFile();
            if (!createNewFile) {
                return false;
            }
            out = new FileOutputStream(f);
            save = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (save) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            context.sendBroadcast(intent);
        }

        Toast.makeText(context, context.getString(R.string.save_image_to_local_hint, f.getPath()), Toast.LENGTH_SHORT).show();
        return save;
    }


    public void setProcessShow(boolean show) {
        processBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putStringArrayList(EXTRA_IMAGES, images);
        outState.putInt(EXTRA_IMAGE_INDEX, imageIndex);
        outState.putBoolean(EXTRA_HAS_SAVE, hasSave);
    }

    protected void onRestoreInstanceStateFromBundle(Bundle savedInstanceState) {
        images = savedInstanceState.getStringArrayList(EXTRA_IMAGES);
        imageIndex = savedInstanceState.getInt(EXTRA_IMAGE_INDEX, 0);
        hasSave = savedInstanceState.getBoolean(EXTRA_HAS_SAVE, false);
    }

    protected void onInitInstanceStateFromIntent() {
        images = getIntent().getStringArrayListExtra(EXTRA_IMAGES);
        imageIndex = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
        hasSave = getIntent().getBooleanExtra(EXTRA_HAS_SAVE, false);
    }
}
